# Copyright (c) 2022 Majjcom
from .bdnet.utils.scode import getRandKey
from .bdnet import client
import threading
import socket


def _creatId():
    return getRandKey()


class _ConnectionRecver(threading.Thread):
    def __init__(self, connObj, callback, pipe, connectionObj):
        super().__init__()
        self._conn = connObj
        self._callback = callback
        self._pipe = pipe
        self._connection = connectionObj

    def run(self):
        while self._pipe[0]:
            try:
                msg = self._conn.recvMsg()
                self._callback(msg, self._connection)
            except socket.timeout:
                pass
            except ConnectionError:
                self._connection.close()
            except OSError:
                self._pipe[0] = False


class Connection:
    def __init__(self, ip, port, recvCallback):
        self._id = _creatId()
        self._ip = ip
        self._port = port
        self._connRecv = client.Connection(ip, port)
        self._connRecv.sendMsg({'id': self._id, 'type': 'recver'})
        self._connSend = client.Connection(ip, port)
        self._connSend.sendMsg({'id': self._id, 'type': 'sender'})
        self._revcCallback = recvCallback
        self._pipe = [True]
        self._recver = _ConnectionRecver(self._connRecv, self._revcCallback, self._pipe, self)
        self._recver.start()

    def sendMsg(self, content: dict):
        self._connSend.sendMsg(content)

    def close(self):
        self._pipe[0] = False
        self._connRecv.close()
        self._connSend.close()



